import React, { useState, useEffect, useRef } from 'react';
import { Button, Form, Input, Select, Col, Row, Tooltip, Table, Pagination, Modal, Radio, message, Upload, TextArea } from 'antd';

import { getListAPI, delAPI, getDetailAPI, addAPI, addBatchAPI,putAPI, uploadIniAPI } from '@/api/modules/equipment/jiaoyantable';
import { ipcApiRoute } from '@/api/main';
import { ipc } from '@/utils/ipcRenderer';
import { checkFiles, parseFiles,startLimit,calculateHash } from '@/utils/formats.js';

export const LocalCheckCom = (props:any) => {
  const {onRender = () => {},refresh = ()=>{}} = props
  const [localCheckDataModalOpen, localCheckDataModalOpenSet] = useState<any>(false);
  const [detail, detailSet] = useState<any>({jiaoyanjieguo:{checkData:[]}});
  const [tableData, tableDataSet] = useState<any>([]);
  const [selectKeys, selectKeysSet] = useState<any>([]);
      // 上传按钮loading
      const [uploadLoading, uploadLoadingSet] = useState(false);
  useEffect(() => {

  }, []);
  // 获取详情
  const handleEditForm = async (record: any, type?: string) => {
    try {
      if (type === 'readonly') {
        record.readonly = true;
      } else {
        record.readonly = false;
      }
      detailSet({...record,jiaoyanjieguo:JSON.parse(record.jiaoyanjieguo as string)});
      localCheckDataModalOpenSet(true)
    } catch (error) {}
  };
  // table
  const columns = [
    {
      title: 'id',
      dataIndex: 'index',
      key: 'index',
      align: 'left',
      render: (text, record, index) => index + 1, // 渲染序号
    },
    {
      title: '名称',
      dataIndex: 'original_filename',
      key: 'original_filename',
      align: 'left',
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      align: 'left',
    },
    // {
    //   title: '校验码',
    //   dataIndex: 'newFilename',
    //   key: 'newFilename',
    //   align: 'left',
    // },

    {
      title: '校验结果',
      dataIndex: 'jiaoyanjieguo',
      key: 'jiaoyanjieguo',
      align: 'left',
      render: (_: any, record: any) => {
        const jiaoyanjieguo = JSON.parse(record.jiaoyanjieguo as string);
        const flag = jiaoyanjieguo.checkStatus === '0';
        return (
          <div>
            {flag ? <span className="blue-color">通过</span> : <span className="red-color">不通过</span>}
          </div>
        );
      },
    },
    {
      title: '校验结果详情',
      dataIndex: 'jiaoyanjieguoxiangqing',
      key: 'jiaoyanjieguoxiangqing',
      align: 'left',
      render: (_: any, record: any) => (
        <div>
          <Button type="link" onClick={() => handleEditForm(record, 'readonly')}>
            校验结果详情
          </Button>
        </div>
      ),
    },
  ] as any;
  const columns2 = [
    {
      title: '参数',
      dataIndex: 'key',
      key: 'key',
      align: 'left',
      width:200,
      ellipsis: true,
    },
    {
      title: '值',
      dataIndex: 'value',
      key: 'value',
      align: 'left',
      render: (_: any, record: any) => <span>{record.status === '1' ? <span className="red-color">{record.value}</span> : record.value}</span>,
      width:150,
      ellipsis: true,      
    },
    {
      title: '期望值',
      dataIndex: 'expected',
      key: 'expected',
      align: 'left',
      width:150,
      ellipsis: true,      
    },
    {
      title: '校验',
      dataIndex: 'status',
      key: 'status',
      align: 'left',
      render: (_: any, record: any) => <span>{record.status === '1' ? <span className="red-color">不通过</span> : '通过'}</span>,
      width:100,
      ellipsis: true,      
    },
    {
      title: '站长备注',
      dataIndex: 'remarks',
      key: 'remarks',
      align: 'left',
      render: (_: any, record: any) => (
        <div>
          {detail.readonly ? (
            <span>{record.remarks}</span>
          ) : (
            <Input
              readOnly={detail.readonly}
              style={{ width: 240 }}
              placeholder="站长备注"
              value={record.remarks}
              allowClear
              onChange={(e) => {
                record.remarks = e.target.value;
                detailSet({ ...detail });
              }}
            />
          )}
        </div>
      ),
    },
  ];
  // row-select
  const rowSelection = {
    selectedRowKeys: selectKeys,
    onChange: (selectedRowKeys: React.Key[]) => {
        selectKeysSet(selectedRowKeys)
    },
  };  
  const syncOfflineData = () => {
    if (selectKeys.length === 0) {
        message.warn('请选择要同步的记录')
    }
    const selectedRows = tableData.filter((item:any) => selectKeys.includes(item.tableId))
    uploadLoadingSet(true)
    selectedRows.forEach((item:any,index:number) => {
        selectedRows[index] = [item]
    })
    // 分多次调用接口
    startLimit([...selectedRows], addBatchAPI, 5, (res) => {
      let selectedRowsArr = selectedRows.map((item:any) => {
        return {
          tableId:item[0].tableId
        }
      })
        ipc
        .invoke(ipcApiRoute.lenodbOperation, {
          tableName: "jiaoyanjieguo_table",
          action: "batchDel",
          batchDelParam:selectedRowsArr
        })
        .then((res:any) => {
            // 刷新数据
            refresh()
            message.success('上传成功')
            uploadLoadingSet(false)
        }); 
    }).catch(()=>{
      uploadLoadingSet(false)
    })
  }
  onRender({tableDataSet,tableData,selectKeysSet})
  return (
    <div className="local-app-container">
      <Row gutter={16}>
        <Col span={24}>
          <div className="l">
            <div className='mb10'>
                <Button  className="" onClick={() => syncOfflineData()} loading={uploadLoading}>
                    上传离线数据到服务器
                </Button>                
            </div>
            <Table height="500px" columns={columns} dataSource={tableData} pagination={false} rowKey="tableId" size="middle" rowSelection={{ type: 'checkbox', fixed: 'left', ...rowSelection}} />
          </div>

          <Modal
            title="本地校验结果"
            open={localCheckDataModalOpen}
            width={800}
            onOk={()=>{
            }}
            onCancel={() =>{
              localCheckDataModalOpenSet(false);
            }}
            footer={[]}
          >
              <div className="check-reslut">数据校验结果：</div>
              <Table
                columns={columns2}
                width="100%"
                scroll={{
                  y: 500,
                }}                
                dataSource={detail.jiaoyanjieguo.checkData}
                pagination={false}
                rowKey="key"
                size="middle"
                height="500px"
                rowClassName={(record) => (record.status === '1' ? 'errorRow' : 'okRow')}
                // loading={loading}
                // 
              />
          </Modal>
        </Col>
      </Row>
    </div>
  );
};

